﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//WB Added
using umbraco;
using umbraco.BusinessLogic;
using umbraco.presentation.masterpages;
using umbraco.uicontrols;
using umbraco.cms.businesslogic.language;
using umbraco.BasePages;
using System.Xml;
using System.IO;


namespace DictionaryTranslate
{
    public class Translate : ApplicationBase
    {
        public Translate()
        {
            //umbraco.presentation.masterpages.umbracoPage.Load +=new umbraco.presentation.masterpages.MasterPageLoadHandler(umbracoPage_Load);
            umbraco.presentation.masterpages.umbracoPage.Load += new MasterPageLoadHandler(umbracoPage_Load);
        
        }

        private umbracoPage _pageReference;
        private string _textToTranslate;
        private string _OriginalLangCode;

        private Control GetPanel1Control(umbracoPage up)
        {
            ContentPlaceHolder cph = (ContentPlaceHolder)up.FindControl("body");
            return cph.FindControl("Panel1");
        }

        void umbracoPage_Load(object sender, EventArgs e)
        {
 	        _pageReference = (umbracoPage)sender;

            string path = _pageReference.Page.Request.Path.ToLower();

            //http://dictionary.translate/umbraco/settings/editDictionaryItem.aspx?id=1
            if (path.EndsWith("settings/editdictionaryitem.aspx") == true)
            {
                Control c2 = GetPanel1Control(_pageReference);

                if (c2 != null)
                {
                    UmbracoPanel panel = (UmbracoPanel)c2;

                    //Insert splitter in menu to make menu nicer on the eye
                    panel.Menu.InsertSplitter();

                    //Add new image button - for our translate button
                    ImageButton translateBtn    = panel.Menu.NewImageButton();
                    translateBtn.ImageUrl       = umbraco.GlobalSettings.Path + "/images/editor/translate.gif";
                    translateBtn.Click         += new ImageClickEventHandler(translateBtn_Click);
                }
            }
        }

        void translateBtn_Click(object sender, ImageClickEventArgs e)
        {
            //Counter for checking number of textboxes filled in
            int numberTextboxesFilledIn = 0;

            //Get the panel on the page
            Control pagePanel = GetPanel1Control(_pageReference);

            //List to store languages
            List<languageTranslateItem> collectionItems = new List<languageTranslateItem>();

            //Check we find it...
            if (pagePanel != null)
            {
                //Convert it to an UmbracoPanel object
                UmbracoPanel panel = (UmbracoPanel)pagePanel;
                                                
                
                foreach (Control ctrl in panel.Controls)
                {
                    
                    //Found the dynamically added pane - with NO ID
                    if (ctrl.GetType().ToString() == "umbraco.uicontrols.Pane")
                    {
                        //For each of the controls found in the dynamically added pane
                        foreach (Control nestedCtrl in ctrl.Controls)
                        {
                            
                            //For each of the textboxes found in the properties
                            foreach (Control nestedAgainCtrl in nestedCtrl.Controls)
                            {                               
                                //If it is a Textbox then....
                                if (nestedAgainCtrl.GetType().ToString() == "System.Web.UI.WebControls.TextBox")
                                {
                                    //Textbox
                                    TextBox languageTextBox = (TextBox)nestedAgainCtrl;                                   

                                    //Get language code from id of textbox
                                    Language lang = new Language(Convert.ToInt32(languageTextBox.ID));                                      

                                    //Check if textbox is NOT empty
                                    if (languageTextBox.Text != string.Empty)
                                    {
                                        //Update counter by 1
                                        numberTextboxesFilledIn += +1;
                                    }

                                    //Store values in object (that will be added to list collection)
                                    languageTranslateItem langTransItem     = new languageTranslateItem();
                                    langTransItem.languageID                = lang.id;              
                                    langTransItem.languageCode              = lang.CultureAlias;    
                                    langTransItem.languageFriendlyName      = lang.FriendlyName;    
                                    langTransItem.langTextBox               = languageTextBox;      
                                    langTransItem.languageTextToTranslate   = string.Empty;         //Default empty string value

                                    //If textbox is empty
                                    if (languageTextBox.Text == string.Empty)
                                    {
                                        //Set the bool flag to true (we need to translate this item)
                                        langTransItem.translateItem = true;
                                    }
                                    else
                                    {
                                        //Set the bool flag to false (this original item we will translate)
                                        langTransItem.translateItem = false;

                                        //Set the text value from the textbox
                                        langTransItem.languageTextToTranslate = languageTextBox.Text;
                                    }

                                    //Add item to list
                                    collectionItems.Add(langTransItem);

                                }
                            }
                        }
                    }
                }
                

                //Error checking....
                if(numberTextboxesFilledIn == 0)
                {
                    //No boxes filled in - display error to user
                    //ShowErrorBubble("Error", "Please fill in one language to do a translation.");
                    ShowSpeechBubble("error", "Error", "Please fill in one language to do a translation.");
                }
                else if(numberTextboxesFilledIn >1)
                {
                    //User has filled in more than one textbox - dipslay error to user
                    //ShowErrorBubble("Error", "Please fill in one only 'one' language to do a translation.");
                    ShowSpeechBubble("error", "Error", "Please fill in one only 'one' language to do a translation.");
                }
                else
                {
                    //All OK - Grab text from the single populated box

                    //Check if AppID is Empty
                    if (getAppID() != string.Empty)
                    {
                        //Only do the translate calls if appID exists

                        //For each of our custom object in the collection of items - find the item we need to translate
                        foreach (languageTranslateItem langTransItem in collectionItems)
                        {
                            //If the item does not need to be translated...
                            if (langTransItem.translateItem == false)
                            {
                                //Translate this text - store this in a string outside of this loop
                                _textToTranslate = langTransItem.languageTextToTranslate;
                                _OriginalLangCode = langTransItem.languageCode;
                            }
                        }

                        foreach (languageTranslateItem langTransItem in collectionItems)
                        {
                            //If the item does need to be translated...
                            if (langTransItem.translateItem == true)
                            {
                                // AppID found - translate this item & update the textbox text with the translation
                                langTransItem.langTextBox.Text = translateItem(_textToTranslate, _OriginalLangCode, langTransItem.languageCode);
                            }
                        }

                        //Done the translation - notify the user with success speech bubble
                        ShowSpeechBubble("success", "Success", "All of your items have been translated");
                    }                                      
                }               
            }            
        }


        //Translate Item stub
        public static string translateItem(string textToTranslate, string originalLanguage, string translatedLanguage)
        {
            string result = string.Empty;

            try
            {
                TranslatorService.LanguageServiceClient client = new DictionaryTranslate.TranslatorService.LanguageServiceClient();

                //App ID, textToTranslate, originaLang, finalLang                
                result = client.Translate(getAppID(), textToTranslate, originalLanguage, translatedLanguage);
            }
            catch (Exception ex)
            {
                // An exception may be thrown if the input text is not valid
                // An exception may be thrown if the to and from language codes are the same
                result = "Error: " + ex.Message;
            }

            return result;

        }

        //Show speech bubble - error message
        /*
        private static void ShowErrorBubble(string title, string exception)
        {
            ((BasePage)HttpContext.Current.Handler).speechBubble(BasePage.speechBubbleIcon.error, title, exception);
        }
        */

        //Show speech bubble
        private static void ShowSpeechBubble(string iconType, string title, string message)
        {    
            switch (iconType)
            {
                case "success":
                    ((BasePage)HttpContext.Current.Handler).speechBubble(BasePage.speechBubbleIcon.success, title, message);
                    break;

                case "error":
                    ((BasePage)HttpContext.Current.Handler).speechBubble(BasePage.speechBubbleIcon.error , title, message);
                    break;

                case "info":
                    ((BasePage)HttpContext.Current.Handler).speechBubble(BasePage.speechBubbleIcon.info , title, message);
                    break;

                case "save":
                    ((BasePage)HttpContext.Current.Handler).speechBubble(BasePage.speechBubbleIcon.save , title, message);
                    break;

                case "warning":
                    ((BasePage)HttpContext.Current.Handler).speechBubble(BasePage.speechBubbleIcon.warning , title, message);
                    break;
            }


            
        }

        private static string getAppID()
        {
            
            string appID = String.Empty;

            //Retrieve settings in config file
            string configFilePath = GlobalSettings.FullpathToRoot + "/config/cws_dictionaryTranslate.config";

            //Check if XML file exists
            if (!File.Exists(configFilePath))
            {
                //Config file does not exist throw error !
                //ShowErrorBubble("Config File", "Config file does not exist.");
                ShowSpeechBubble("error", "Config File", "Config file does not exist.");
            }
            else
            {
                //Load the XML doc
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(configFilePath);

                //Select the root node <dictionaryTranslate>
                XmlNode rootNode = xmlDoc.DocumentElement;

                //<appID key="C1CC44B600CAAABE93074D68F34F51F6EA9697DF" />
                appID = rootNode.SelectSingleNode("appID").Attributes.GetNamedItem("key").Value;

                if (appID == string.Empty)
                {
                    //We don't have an AppID, so we can't Tranlsate -Show error
                    //ShowErrorBubble("No AppID found", "No AppID can be found in the config file");
                    ShowSpeechBubble("error", "No AppID found", "No AppID can be found in the config file");
                }
            }            


            return appID;
        }


    }

    public class languageTranslateItem
    {
        public int      languageID                  { get; set; }
        public string   languageCode                { get; set; }
        public string   languageFriendlyName        { get; set; }
        public string   languageTextToTranslate     { get; set; }
        public bool     translateItem               { get; set; }
        public TextBox  langTextBox                 { get; set; }
    }
}
